﻿@using GameSchool.HtmlHelpers
@model GameSchool.ViewModels.Video.WatchViewModel
@{
    ViewBag.Title = "Watch";
}
<script type="text/css">

</script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
<h2>@Model.video.Name</h2>
<video width="700" height="390" controls>
    <source src="@string.Format("/Content/Videos/{0}.mp4", @Model.video.VideoID)" type='video/mp4; codecs="avc1.42E01E, mp4a.40.2"'>
</video>
<p>@Model.video.VideoFilePath</p>
<button class="likeButton" value="${ID}">
    Like</button>
<div class="rightIt">
    Myndbandið var birt þann @Model.video.LastUpdated</div>
<div style="height: 2px; background-color: #EEE; text-align: center; margin-bottom: 15px;
    margin-top: 15px;">
    <span style="background-color: white; position: relative; top: -0.7em;"><strong>Lýsing</strong>
    </span>
</div>
<div class="centerIt">
    @Model.video.Description
</div>
<div style="height: 2px; background-color: #EEE; text-align: center; margin-bottom: 15px;
    margin-top: 15px;">
    <span style="background-color: white; position: relative; top: -0.7em;"><strong>Athugasemdir</strong>
    </span>
</div>
<ul class="commentList">
    <li class="commentAdd" id="commentAdd">
        <input type="hidden" id="LastVisited" value="@DateTime.Now" />
        <textarea id="CommentText" name="CommentText" rows="3" cols="20"></textarea>
        <label>
            <button id="btnAddComment">
                Add comment</button>
        </label>
        @Html.ValidationMessage("CommentText")
    </li>
</ul>
<script id="commentTemplate" type="text/html">
	<li id="comments">
		<a href="http://www.ru.is"><img src='@Url.Content("~/Content/images/User.png")' alt="User" /></a>
		<div class="commentBody">
			<a href="http://www.ru.is">${UserName}</a>
			<span>${CommentText}</span>
			<div>
				<abbr class="commentDate" title='${CommentDate}'>${toShortDate( CommentDate ) }</abbr>
				<button class="likeButton" value="${ID}" >Like</button>
                @if (User.IsInRole("Kennari"))
                {    
                <button class="deleteButton" value="${ID}">Delete comment</button>
                }
			</div>
		</div>
	</li>
</script>
<!-- Usually, the script should be moved to a separate file. -->
<script type="text/javascript">

    $(document).ready(function () {
        $("#btnAddComment").live('click', function (event) {
            event.preventDefault();
            
            var text = $("#CommentText").val();

            if (text.length > 0) {
                var dt = $("#LastVisited").val();

                var param = {
                    CommentText: text,
                    LastVisited: dt
                };
                $.post("/Video/AddComment/@Model.video.VideoID", param, function (data) {
                    processComments(data.Comments);
                    $("#LastVisited").val(data.LastVisited);
                    $('#CommentText').val('');
                });
            }
            else {
                $("#CommentText").val("Please add something to the comment!");
            }
        });

        // This is perhaps the most tricky part of getting the like buttons to work under 
        // all circumstances. Since the comments - and therefore the like buttons as well - 
        // are always generated client side in our case, and are always generated AFTER 
        // the page has been loaded, they simply don't exist at this point. Meaning that if
        // we would use the normal jquery $().click() function, it would have no elements to
        // assign the click event handler to. However, using the live() function (or the on()
        // function if we were using the latest version of jquery), we can create event handlers
        // for elements that haven't been created yet.
        //

        $(".likeButton").live("click", function () {
            var btn = this;
            var commentID = $(this).val();

            var param = { CommentID: commentID };

            $.post("/Video/AddLike", param, function (data) {
                var strTitle = processLikeList(data);
                $(btn).attr("title", strTitle);
            });
        });

        // Similarly, to allow admins to remove comments:
        $(".deleteButton").live("click", function (event) {
            event.preventDefault();
            
            var button = $(this);
            var commentId = $(this).val();
            console.log(commentId);

            $.post("/Video/DeleteComment/" + commentId, function (data) {
                location.reload();
                var listItem = button.find('li.comments');
                console.log(listItem);
                listItem.remove();
            });

        });

        // Finally, load comments using Ajax. This happens at document.ready
        // time.
        $.getJSON("/Video/GetComments/@Model.video.VideoID", undefined, function (data) {
            processComments(data);
        });

        // It would be nice to add code which would execute approximately every minute
        // (using the setInterval() javascript function), which would update
        // the time values just like Facebook does, i.e. where "1 minute ago" converts
        // to "2 minutes ago" etc. The pseudocode goes something like this:
        //
        //        setInterval(function () {
        //            // Get access to all the <abbr> elements with class "commentDate":
        //            $(".commentDate").each(function () {
        //                // Get the date value for each. The real date value is stored in
        //                // the title, while Facebook uses a custom (HTML5) data-utime attribute.
        //                var dt = $(this).title();
        //                // Update the text of the element, with a (possibly new) text value:
        //                $(this).text(toShortDate(dt));
        //            });
        //        }, 60000);  // ... and do this once every minute...

    });

    // A few helper functions, mostly to try to keep things DRY:

    function processComments(data) {
        for (var i = 0; i < data.length; i++) {
            data[i].CommentDate = ConvertStringToJSDate(data[i].CommentDate);
        }

        $("#commentTemplate").tmpl(data).insertBefore("#commentAdd");
    }

    function processLikeList(data) {

        // In this case we implement things in a similar way as Facebook does it.
        // If we would want to display the user names of all those who have liked
        // the comment, we could do that with a simple JavaScript statement:

        // var strList = data.join( ", " );
        // http://www.w3schools.com/jsref/jsref_join.asp

        var strLikeString = "";
        if (data.length > 2) {
            strLikeString = data[0].UserName + ", " + data[1].UserName + " and " + (data.length - 2) + " others like this";
        }
        else if (data.length == 2) {
            strLikeString = data[0].UserName + " and " + data[1].UserName + " like this";
        }
        else if (data.length == 1) {
            strLikeString = data[0].UserName + " likes this";
        }

        return strLikeString;
    }

    // The function provided in the project description, which converts the date string
    // received in the JSON message into a JavaScript Date() object.
    function ConvertStringToJSDate(dt) {
        var dtE = /^\/Date\((-?[0-9]+)\)\/$/.exec(dt);
        if (dtE) {
            var dt = new Date(parseInt(dtE[1], 10));
            return dt;
        }
        return null;
    }

    // A simple helper function which converts the date for a given comment
    // into a readable string, similar to what Facebook does.
    function toShortDate(dt) {
        var currentTime = new Date();
        // Subtracting two dates gives us difference in millliseconds,
        // which we then convert to seconds:
        var diff = (currentTime - dt) / 1000;

        if (diff < 10) {
            return "a few seconds ago";
        }
        else if (diff >= 10 && diff < 60) {
            return "less than a minute ago";
        }
        else if (diff >= 60 && diff < 120) {
            return "1 minute ago";
        }
        else if (diff >= 120 && diff < 3600) {
            var minutes = parseInt(diff / 60);
            return minutes + " minutes ago";
        }
        else if (diff >= 3600 && diff < 86400) {
            var hours = parseInt(diff / 360);
            return hours + " hours ago";
        }
        else {
            return "more than one day ago";
        }
    }

</script>
